import React, {ChangeEvent, FC, InputHTMLAttributes, ReactElement} from "react";
import Icon from "../Icon/icon";
import classNames from "classnames";
import {IconProp} from "@fortawesome/fontawesome-svg-core";

type InputSize = "lg" | 'sm'

/**
 * Omit<InputHTMLAttributes<HTMLElement>, 'size' > 排除size属性
 */

export interface InputProps extends Omit<InputHTMLAttributes<HTMLElement>, 'size'> {
  /**
   * 是否禁用
   */
  disabled?: boolean
  /** 设置input大小 ，支持lg或者是sm*/
  size?: "lg" | 'sm'
  /** 添加图标，在右侧悬浮添加一个图标，用于提示*/
  icon?: IconProp
  /** 添加后缀，用于配合一些固定组合*/
  append?: string | ReactElement
  /** 添加前缀，用于配合一些固定组合*/
  prepend?: string | ReactElement
  /**
   * 监听输入事件
   * @param e
   */
  onChange?: (e: ChangeEvent<HTMLInputElement>) => void
}

export const Input: FC<InputProps> = (props) => {
  const {style, className, disabled, size, icon, append, prepend, ...restProps} = props

  const classes = classNames("viking-input-wrapper", className, {
    [`input-size-${size}`]: size,
    'is-disabled': disabled,
    'input-group': prepend || append,
    'input-group-append': !!append,
    'input-group-prepend': !!prepend
  })

  const fixControlledValue = (value: any) => {
    if (typeof value === 'undefined' || value === null) {
      return ''
    }
    return value
  }


  // 因为受控组件和非受控组件不能写在一起，如果value存在，就删除defaultValue
  if ("value" in props) {
    delete restProps.defaultValue
    restProps.value = fixControlledValue(restProps.value)
  }


  return (
    <div className={classes} style={style}>
      {prepend && <div className="viking-input-group-prepend">{prepend}</div>}

      <div className='viking-input-icon-wrapper'>
        {icon && <div className="icon-wrapper"><Icon icon={icon} title={`title-${icon}`}/></div>}
        <input className="viking-input-inner" disabled={disabled} {...restProps} />
      </div>


      {append && <div className='viking-input-group-append'>{append}</div>}

    </div>
  )
}

export default Input
